<template>
  <div class="member pad">
    <div class="head">
      <span>学校统计</span>
    </div>
    <div class="member-head">
      <div class="m-t-b">
        <span style="padding-right: 20px">所在省市: </span>
        <el-select
          v-model="selectedProvince"
          clearable
          filterable
          placeholder="请选择省份"
          :loading="provinceLoading"
          @change="ProvinceInput"
          :disabled="canSelect"
        >
          <el-option v-for="(item, i) in provinces" :key="i" :value="item.id" :label="item.cname"></el-option>
        </el-select>

        <el-select
          v-model="selectedCity"
          clearable
          filterable
          placeholder="请选择城市"
          style="margin: 0 20px;"
         @change="CityInput"
        >
          <el-option v-for="(item, i) in cities" :key="i" :value="item.id" :label="item.cname"></el-option>
        </el-select>
      </div>
      <div class="m-t-b">
        <span style="padding-right: 20px;">学校信息: </span>
        <el-select
          v-model="selectedSchool"
          clearable
          filterable
          placeholder="请选择学校"
          :loading="schoolLoading"
          @change="schoolInput"
          :disabled="canSelect"
        >
          <el-option v-for="(item) in schools" :key="item.enterpriseName" :value="item.enterpriseName" :label="item.enterpriseName"></el-option>
        </el-select>
        <el-select
          v-model="selectedGrade"
          clearable
          filterable
          :loading="gradeLoading"
          placeholder="请选择年级"
          style="margin: 0 20px;"
          @change="gradeInput"
        >
          <el-option v-for="(item, i) in grades" :key="i" :value="item.grade" :label="item.grade"></el-option>
        </el-select>
        <el-select
          v-model="selectedClass"
          clearable
          filterable
          :loading="classLoading"
          placeholder="请选择班级"
          @change="classInput"
        >
          <el-option v-for="(item, i) in classes" :key="i" :value="item.grades" :label="item.grades"></el-option>
        </el-select>
      </div>
      <div class="m-t-b">
        <span style="padding-right: 20px;">查询日期: </span>
        <!-- <el-date-picker
          v-model="dateArr"
          type="date"
          value-format="yyyy-MM-dd">
        </el-date-picker> -->
        <el-date-picker
          v-model="dateArr"
          clearable
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </div>
      <div class="m-t-b">
        <el-button :loading="isSearching" type=primary @click="searchSchool">
          <i class="el-icon-search"></i>
          查询
        </el-button>
        <el-button type=primary @click="exportExcel">
          <i class="el-icon-download"></i>
          导出Excel
        </el-button>
      </div>
    </div>
    <div class="split-line" v-if="selectedSchool">
      <div>
        <span>{{selectedSchool}}</span>
        <span v-if="selectedGrade"> - {{selectedGrade}}年级</span>
        <span v-if="selectedClass"> - {{selectedClass}}班</span>
        <span v-if="peopleNum === 0 || peopleNum">({{peopleNum}}人)</span>
      </div>
    </div>
    <div
      v-if="ifHasData"
      class="no-statistics"
    >
      暂无相关统计数据
    </div>
    <div v-if="gradeOrClassDistribution.length">
      <span class="m-title">{{type === 1 ? '年级人数分布' : '班级人数分布'}}</span>
      <el-table stripe border :data="gradeOrClassDistribution">
        <el-table-column align="center" :label="type === 1 ? '年级' : '班级'" prop="label"></el-table-column>
        <el-table-column align="center" label="人数">
          <template slot-scope="scope">
            {{scope.row.rate}}
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-if="genderDistribution.length">
      <span class="m-title">性别分布</span>
      <el-table stripe border :data="genderDistribution">
        <el-table-column align="center" label="性别" prop="label"></el-table-column>
        <el-table-column align="center" label="人数">
          <template slot-scope="scope">
            {{scope.row.rate}}
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-if="ageDistribution.length">
      <span class="m-title">年龄分布</span>
      <el-table stripe border :data="ageDistribution">
        <el-table-column align="center" label="年龄" prop="label"></el-table-column>
        <el-table-column align="center" label="人数">
          <template slot-scope="scope">
            {{scope.row.rate}}
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-if="resultDistribution.length">
      <span class="m-title">健康测评结果分布</span>
      <el-table stripe border :data="resultDistribution">
        <el-table-column align="center" label="结果" prop="label"></el-table-column>
        <el-table-column align="center" label="所占比例">
          <template slot-scope="scope">
            {{scope.row.rate}}
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-if="ageusiaDistribution.length">
      <span class="m-title">健康测评缺乏症分布</span>
      <el-table stripe border :data="ageusiaDistribution">
        <el-table-column align="center" label="缺乏症" prop="label"></el-table-column>
        <el-table-column align="center" label="所占比例">
          <template slot-scope="scope">
            {{scope.row.rate}}
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-if="questionDistribution.length">
      <span class="m-title">健康测评问题填写情况分布</span>
      <el-table stripe border :data="questionDistribution">
        <el-table-column align="center" label="问题及答案" prop="label"></el-table-column>
        <!-- <el-table-column align="center" label="所选答案" prop="answer"></el-table-column> -->
        <el-table-column align="center" label="所占比例">
          <template slot-scope="scope">
            {{scope.row.rate}}
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- <el-table stripe border class="m-t-b" :data="infos">
      <el-table-column label="标签名" prop="label"></el-table-column>
      <el-table-column label="比例" prop="rate"></el-table-column>
    </el-table> -->
  </div>
</template>
<script>
import json2Excel from '../util/json2Excel';
import {
  getAllSchool,
  getGradesBySchoolName,
  getClassBySchoolAndGrade,
  getSchoolStatisticsInfo
} from '../api';
import { mapStr2Json, formatDate } from '../util/index';
import {
  getSchoolInfo,
  getGradeInfo,
  getProvinceInfo,
  getCityInfo,
} from '../api/version2';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';

export default {
  name: 'memberConsume',
  data () {
    return {
      selectedSchool: '',
      selectedGrade: '',
      selectedClass: '',
      selectedProvince: '',
      selectedCity: '',
      provinceLoading: false,
      cityLoading: false,
      schoolLoading: false,
      gradeLoading: false,
      classLoading: false,
      // dateArr: '',
      dateArr: ["",""],
      schools: [],
      grades: [],
      provinces: [],
      cities: [],
      createDate: '',
      flag: false,
      type: 1,
      classes: [],
      isSearching: false,
      peopleNum: '',
      ageDistribution: [], // 年龄分布
      ageusiaDistribution: [], // 缺乏症分布
      questionDistribution: [], // 问题分布
      resultDistribution: [], // 结果分布
      genderDistribution: [], // 性别分布
      gradeOrClassDistribution: [], // 年级或班级分布
      canSelect: false,

    }
  },
  methods: {
    ProvinceInput() { //省份输入
    this.resetData();
    this.selectedSchool = '';
    this.selectedGrade = '';
    this.selectedClass = '';
    this.selectedCity = "";
    this.cities = [];
    this.grades = [];
    this.classes = [];
    if(this.selectedProvince) {
      this.fetchCity(this.selectedProvince);
      this.fetchSchoolByProvince(this.selectedProvince);
    }
   },
   CityInput(){  //城市输入
     this.fetchSchoolByCity(this.selectedCity);
   },
    schoolInput () { // 学校输入
      this.resetData();
      this.selectedGrade = '';
      this.selectedClass = '';
      this.grades = [];
      this.classes = [];
      if (this.selectedSchool) {
        this.fetchGrade(this.selectedSchool)
      }
    },
    gradeInput () { // 年级输入
      this.resetData();
      this.selectedClass = '';
      this.classes = [];
      if (this.selectedGrade) {
        this.fetchClass(this.selectedSchool, this.selectedGrade)
      }
    },
    classInput () { // 班级输入
      this.resetData()
    },
    searchSchool () { // 查询学校信息
      if (!this.$checkAuth('canComputeSchool')) {
        return this.$message.error('暂无对应操作权限!')
      };
      if (!this.selectedSchool) {
        return this.$message.error('查询条件不能为空!')
      };
      if (this.selectedGrade && !this.selectedClass) { // 按照年级统计
        this.type = 2;
        this.fetchSchoolStatistics(2, this.selectedSchool, this.selectedGrade, null, this.dateArr)
      } else if (this.selectedGrade && this.selectedClass) { // 按照班级统计
        this.type = 3;
        this.fetchSchoolStatistics(3, this.selectedSchool, this.selectedGrade, this.selectedClass, this.dateArr)
      } else if (!this.selectedGrade && !this.selectedClass) { // 按照学校统计
        this.type = 1;
        this.fetchSchoolStatistics(1, this.selectedSchool, null, null, this.dateArr)
      }
    },
    exportExcel () { // 导出excel
      if (!this.$checkAuth('canExportExcel')) {
        return this.$message.error('暂无对应操作权限!')
      };
      if (this.checkIfHasData()) {
        return this.$message.error('无导出数据!')
      };
      let jsonData = [
        { label: '年级人数分布', rate: '', isTitle: true }
      ]
      .concat(this.gradeOrClassDistribution)
      .concat([{ label: '性别人数分布', rate: '', isTitle: true }])
      .concat(this.genderDistribution)
      .concat([{ label: '年龄人数分布', rate: '', isTitle: true }])
      .concat(this.ageDistribution)
      .concat([{ label: '健康测评结果比例分布', rate: '', isTitle: true }])
      .concat(this.resultDistribution)
      .concat([{ label: '健康测评缺乏症比例分布', rate: '', isTitle: true }])
      .concat(this.ageusiaDistribution)
      .concat([{ label: '健康测评问题填写比例分布', rate: '', isTitle: true }])
      .concat(this.questionDistribution);
      let fileName = undefined;
      let date = formatDate(this.createDate, 'ZH');
      if (this.type === 1) {
        fileName = `${this.selectedSchool}(${date}统计)`
      } else if (this.type === 2) {
        fileName = `${this.selectedSchool}-${this.selectedGrade}年级(${date}统计)`
      } else if (this.type === 3) {
        fileName = `${this.selectedSchool}-${this.selectedGrade}年级-${this.selectedClass}班(${date}统计)`
      };
      json2Excel(jsonData, fileName, ['项目名称', '比例/人数'], [], fileName)
    },
    fetchCity(Id) { // 获取城市信息
      // this.provinceLoading = true;
      getCityInfo({
        id: Id
      }).then(res => {
        this.cities = res.data.data || [];
      })
    },
    fetchAllSchool () { // 获取学校信息
      this.schoolLoading = true;
      getSchoolInfo({
        type: 1,
      })
      .then(res => {
        this.schoolLoading = false;
        if (res.data.code === 1) {
          this.schools = res.data.data || []
        } else {
          this.$message.error(res.data.msg || '网络异常!')
        }
      })
      .catch(e => {
        this.schoolLoading = false;
        this.$message.error('网络异常!')
      })
    },
    fetchSchoolByProvince(provinceId){ //查询所有学校（根据省份）
      getSchoolInfo({
        provinceId: provinceId,
        type: 1,
      }).then(res => {
        this.schools = res.data.data || [];
      })
    },
    fetchSchoolByCity(cityId){ //查询所有学校（根据城市）
    getSchoolInfo({
      cityId: cityId,
      type: 1,
    }).then(res => {
      this.schools = res.data.data || [];
    })
    },
    fetchGrade (schoolName) { // 获取年级
      this.gradeLoading = true;
      getGradeInfo({
        enterpriseName: schoolName,
      })
      .then(res => {
        console.log(res);
        this.gradeLoading = false;
        if (res.data.code === 1) {
          this.grades = res.data.data || []
        } else {
          this.$message.error(res.data.msg || '网络异常!')
        }
      })
      .catch(e => {
        this.gradeLoading = false;
        this.$message.error('网络异常!')
      })
    },
    fetchClass (schoolName, gradeName) { // 获取班级
      this.classLoading = true;
      getGradeInfo({
        enterpriseName: schoolName,
        grade: gradeName,
      })
      .then(res => {
        console.log(res);
        this.classLoading = false;
        if (res.data.code === 1) {
          this.classes = res.data.data || []
        } else {
          this.$message.error(res.data.msg || '网络异常!')
        }
      })
      .catch(e => {
        this.classLoading = false;
        this.$message.error('网络异常!')
      })
    },
    resetData () {
      this.peopleNum = '';
      this.createDate = '';
      this.ageDistribution = []; // 年龄分布
      this.ageusiaDistribution = []; // 缺乏症分布
      this.questionDistribution = []; // 问题分布
      this.resultDistribution = []; // 结果分布
      this.genderDistribution = []; // 性别分布
      this.gradeOrClassDistribution = [] // 年级或班级分布
    },
    checkIfHasData () {
      return (!this.gradeOrClassDistribution.length && !this.genderDistribution.length && !this.ageDistribution.length && !this.resultDistribution.length && !this.ageusiaDistribution.length && !this.questionDistribution.length)
    },
    fetchSchoolStatistics (type, schoolName, gardeName, className, date) { // 获取学校统计信息
      NProgress.start();
      this.isSearching = true;
      this.resetData();
      schoolName = schoolName || null;
      gardeName = gardeName || null;
      className = className || null;
      date = date || null;
      let startDate = null;
      let endDate = null;
      if (date) {
        // startDate = date + ' 00:00:00';
        // endDate = date + ' 23:59:59'
        startDate = date[0];
        endDate = date[1];
      };
      getSchoolStatisticsInfo({
        type,
        schoolName,
        gardeName,
        className,
        startDate,
        endDate,
      })
      .then(res => {
        console.log(res);
        if (res.data.code === 1) {
          NProgress.done();
          let data = res.data.data;
          let {
            ageProportion,
            ageusiaProportion,
            questionProportion,
            resultProportion,
            sexProportion,
            gardeList,
            createDate,
            peopleNum
          } = data;
          this.peopleNum = peopleNum;
          this.createDate = createDate;
          this.ageDistribution = mapStr2Json(ageProportion).filter(item => item.rate).map(item => {
            return {
              label: item.label + '岁',
              rate: item.rate + '人'
            }
          });
          this.ageusiaDistribution = mapStr2Json(ageusiaProportion).filter(item => item.rate).map(item => {
            return {
              label: item.label,
              rate: item.rate + '%'
            }
          });
          let questionDistribution = mapStr2Json(questionProportion).filter(item => item.rate).map(item => {
            let arr = item.label.split('#');
            return {
              label: arr[0],
              answer: arr[2],
              rate: item.rate + '%'
            }
          });
          let tempObj = {};
          let tempArr = [];
          let len = questionDistribution.length;
          for (let i = 0; i < len; i ++) {
            if (!tempObj[questionDistribution[i].label]) {
              tempObj[questionDistribution[i].label] = [questionDistribution[i]]
            } else {
              tempObj[questionDistribution[i].label].push(questionDistribution[i])
            }
          };
          for (let key in tempObj) {
            for (let j = 0; j < tempObj[key].length; j ++) {
              tempArr.push(tempObj[key][j])
            }
          };
          this.questionDistribution = tempArr.map(item => {
            return {
              label: `问题: ${item.label} # 答案: ${item.answer}`,
              rate: item.rate
            }
          });
          tempObj = null;
          tempArr = null;
          this.resultDistribution = mapStr2Json(resultProportion).filter(item => item.rate).map(item => {
            return {
              label: item.label,
              rate: item.rate + '%'
            }
          });
          this.gradeOrClassDistribution = gardeList ? (gardeList.map(item => {
            return {
              label: item.name + (this.type === 1 ? '年级' : '班'),
              rate: item.peopleNum + '人'
            }
          })) : [];
          this.genderDistribution = mapStr2Json(sexProportion).filter(item => item.rate).map(item => {
            return {
              label: item.label == '1' ? '男' : '女',
              rate: item.rate + '人'
            }
          })
        } else {
          NProgress.done();
          this.$message.error(res.data.msg || '网络异常!')
        };
        this.isSearching = false
      })
      .catch(e => {
        NProgress.done();
        this.isSearching = false;
        this.$message.error('网络异常!')
      })
    }
  },
  created () {
    let roleId = sessionStorage.getItem('role');
    let name = sessionStorage.getItem('username');
    if (roleId == 14) { // 学校
      this.canSelect = true;
      this.selectedSchool = name;
      this.fetchGrade(name)
    } else {
      this.fetchAllSchool();
    };
    getProvinceInfo({
      ctype: 1,
    }).then(res => {
      this.provinces = res.data.data || [];
    })
  },
  computed: {
    ifHasData () {
      return (!this.gradeOrClassDistribution.length && !this.genderDistribution.length && !this.ageDistribution.length && !this.resultDistribution.length && !this.ageusiaDistribution.length && !this.questionDistribution.length)
    }
  }
}
</script>
<style lang="scss">
  .member {
    .member-head {
      margin-top: 20px;
      padding: 20px;
      background-color: #f6f6f6;
      border-radius: 6px;
    }
    .no-statistics {
      margin-top: 50px;
      text-align: center;
      color: #707070;
    }
    .split-line {
      margin-top: 40px;
      position: relative;
      height: 2px;
      background-color: #4AC493;
      div {
        padding: 0 10px;
        position: absolute;
        display: inline-block;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        background-color: #ffffff;
        z-index: 3;
        span {
          color: #4AC493;
          font-size: 20px;
          font-weight: bold;
        }
      }
    }
    .m-title {
      margin: 30px 0 20px 0;
      display: inline-block;
      padding: 8px 20px;
      background-color: #4AC493;
      color: #ffffff;
      font-weight: bold;
      font-size: 16px;
      border-top-right-radius: 40px;
      border-bottom-right-radius: 40px;
    }
  }
</style>
